var fs          = require('fs'),
    path        = require('path'),
    gulp        = require('gulp'),

    // 
    // nodemon     = require('gulp-nodemon'),

    // 阻止由于gulp 插件生成的错误而导致的管道中断；
    // plumber     = require('gulp-plumber'),

    // livereload  = require('gulp-livereload'),

    // 使用 UglifyJS3 压缩文件；
    uglify      = require('gulp-uglify'),

    // 
    sass        = require('gulp-sass'),

    // 多个文件的内容，合到一个文件中去；可以指定顺序、换行符等。
    // concat      = require('gulp-concat'),

    rename      = require('gulp-rename'),

    // revision
    // n.   (一项、一轮等) 修订，修改; 修订，修改(的进行); 复习; 温习;
    // unicorn.css → unicorn-d41d8cd98f.css;
    rev         = require('gulp-rev'),

    // 删除或者替换文件的相对路径；
    flatten     = require('gulp-flatten'),

    // 目前已经被 gulp-htmlmin 替代了；
    htmlmin     = require('gulp-minify-html'),

    // jshint      = require('gulp-jshint'),
    
    // 有条件的执行；
    // gulpif      = require('gulp-if'),
    
    clean       = require('gulp-clean'),
    
    // 
    // es          = require('event-stream'),    
    // parse       = require('esprima').parse,
    // toString    = require('escodegen').generate,
    confusion   = require('confusion'),

    // 运行指定顺序的一系列 gulp 任务；
    runSequence = require('run-sequence'),

    // stylish     = require('jshint-stylish'),

    // 使用 gulp-rev 为静态资源添加hash，然后使用此插件替换 html 中的相应的引用资源；
    revCollector = require('gulp-rev-collector'),
    // browserSync = require('browser-sync').create(),
    // config = require('./config/config'),
    // sceneVariable = config.app.name,
    // sceneVariable = 'development',
    sceneVariable = process.env.NODE_ENV || 'development',
    paths = {
        wxVerify:'./asset/*.txt',
        favicon:'./asset/favicon.ico',
        pages: './app/views/**/*',
        
        sass: './asset/sass/**/*.scss',
        font: './asset/font/*',
        audio: './asset/audio/**/*',
        images: './asset/image/**/*',
        script: './asset/js/**/*.js',

        minifyjs: './asset/js/**/*.js',

        componentHtml: './asset/component/**/*.html',
        componentJs: './asset/component/**/*.js',
        componentScss: './asset/component/**/*.scss',
        componentCss: './asset/component/**/*.css',

        // 资源添加hash 前后的映射；
        revPath: './public/revpath/'
    };

console.log(sceneVariable);

// n.  不确定; 困惑; 混淆; 混同; 困窘; 尴尬; 局促不安;
var confusionGulp = function () {
    return es.map(function (file, callback) {
        if (file.isNull()) {
            return callback(null, file);
        }
        var ast = parse(fs.readFileSync(file.path));
        var obfuscated = confusion.transformAst(ast, confusion.createVariableName);
        file.contents = new Buffer(toString(obfuscated));
        return callback(null, file);
    });
}

// 文本文件
gulp.task('wxVerify', function () {
    gulp.src(paths.wxVerify)
        .pipe(gulp.dest('./public'));
});

// 网站logo
gulp.task('favicon', function () {
    gulp.src(paths.favicon)
        .pipe(gulp.dest('./public'));
});

// 音频文件
gulp.task('audio', function () {
    gulp.src(paths.audio)
        .pipe(gulp.dest('./public/audio'));
});

// 图片
gulp.task('image', function() {
    if(sceneVariable == 'development'){
        gulp.src(paths.images)
            .pipe(gulp.dest('./public/image'));
    }else{
        gulp.src(paths.images)
            // .pipe(rev())
            .pipe(gulp.dest('./public/image'))
            .pipe(rev.manifest())
            .pipe(gulp.dest(paths.revPath+'/image'));
    }
});

// 字体文件
gulp.task('font', function () {
    if(sceneVariable=='development'){
        gulp.src(paths.font)
            .pipe(gulp.dest('./public/font'))
    }else {
        gulp.src(paths.font)
            // .pipe(rev())
            .pipe(gulp.dest('./public/font'))
            .pipe(rev.manifest())                           // 生成版本号地图
            .pipe(gulp.dest(paths.revPath + '/font'));
    }
});

// 公用组件
gulp.task('component', function() {
    if (sceneVariable == 'development') {
        gulp.src(paths.componentHtml)
            .pipe(gulp.dest('./public/component'));
        gulp.src(paths.componentJs)
            .pipe(gulp.dest('./public/component'));
        gulp.src(paths.componentCss)
            .pipe(gulp.dest('./public/component'));
        gulp.src(paths.componentScss)
            // .pipe(plumber())
            // .pipe(sass({outputStyle: 'compressed'}))// nested<default>, expanded, compact, compressed;
            // .pipe(sass({outputStyle: 'nested'}))// 这里是第三方组件，通常就是压缩版的css文件，所以就不需要执行编译和压缩。
            .pipe(gulp.dest('./public/component'));
    } else {
        gulp.src(paths.componentHtml)
            // .pipe(rev())
            .pipe(gulp.dest('./public/component'))
            .pipe(rev.manifest())
            .pipe(gulp.dest(paths.revPath + '/component/html'));
        gulp.src(paths.componentJs)
            .pipe(uglify({
                // v.   压碎; 撕烂; 严重损坏; 糟蹋(如蹩脚的诗朗诵或拙劣的演奏);
                // 重置变量名；
                mangle: true,
                output: {
                    beautify: true
                },
                compress: true
            }))
            .pipe(confusionGulp())
            // .pipe(uglify())// 有两个，会不会多余；
            // .pipe(rev())
            .pipe(gulp.dest('./public/component'))
            .pipe(rev.manifest())
            .pipe(gulp.dest(paths.revPath + '/component/js'));
        gulp.src(paths.componentCss)
            // .pipe(rev())
            .pipe(gulp.dest('./public/component'))
            .pipe(rev.manifest())
            .pipe(gulp.dest(paths.revPath + '/component/css'));
        gulp.src(paths.componentScss)
            // .pipe(plumber())
            .pipe(sass({outputStyle: 'compressed'}))
            // .pipe(rev())
            .pipe(gulp.dest('./public/component'))
            .pipe(rev.manifest())
            .pipe(gulp.dest(paths.revPath + '/component/scss'));
    }
});

// sass
gulp.task('sass', function () {
    if (sceneVariable == 'development') {
        gulp.src(paths.sass)
            // .pipe(plumber())
            // .pipe(sass({
            //     outputStyle: 'compressed'
            // }))
            .pipe(sass({outputStyle: 'expanded'}))
            .pipe(gulp.dest('./public/css'));
    } else {
        gulp.src(paths.sass)
            // .pipe(plumber())
            // .pipe(sass({outputStyle: 'compressed'}))
            .pipe(sass({outputStyle: 'expanded'}))
            // .pipe(rev())
            .pipe(gulp.dest('./public/css'))
            .pipe(rev.manifest())
            .pipe(gulp.dest(paths.revPath + '/css'));
    }
});

// 压缩js任务
gulp.task('minifyjs', function() {
    if (sceneVariable == 'development') {
        gulp.src([paths.minifyjs,'!./asset/js/**/config-*.js'])
            .pipe(gulp.dest('./public/js'));                // 压缩之后的js文件输出目录
        // gulp.src(['./asset/js/base/config-' + sceneVariable + '.js'])
        //     .pipe(rename('config-static-wap.js'))
        //     .pipe(gulp.dest('./public/js/base'));                // 压缩之后的js文件输出目录
    } else {
        gulp.src([paths.minifyjs,'!./asset/js/**/config-*.js'])
            .pipe(uglify({
                mangle: true,
                output: {
                    beautify: true
                },
                compress: true
            }))
            .pipe(confusionGulp())
            .pipe(uglify())
            // .pipe(rev())                                    // 生成相关版本号
            .pipe(gulp.dest('./public/js'))                 // 压缩之后的js文件输出目录
            .pipe(rev.manifest())                           // 生成版本号地图
            .pipe(gulp.dest(paths.revPath + '/js'));        // 输出地图文件目录
        gulp.src(['./asset/js/base/config-' + sceneVariable + '.js'])
            .pipe(uglify({
                mangle: true,
                output: {
                    beautify: true
                },
                compress: true
            }))
            .pipe(confusionGulp())
            .pipe(rename('config-static-wap.js'))
            .pipe(uglify())
            // .pipe(rev())                                    // 生成相关版本号
            .pipe(gulp.dest('./public/js/base'))            // 压缩之后的js文件输出目录
            .pipe(rev.manifest())                           // 生成版本号地图
            .pipe(gulp.dest(paths.revPath + '/js/base'));   // 输出地图文件目录
    }
});

// 公用组件
gulp.task('pages', function() {
    if(sceneVariable=='development'){
        return gulp.src(paths.pages)
            // .pipe(gulpif(
            //     true, 
            //     htmlmin({
            //         empty: true,
            //         spare: true,
            //         quotes: true
            //     })
            // ))
            // .pipe(htmlmin({empty: true, spare: true, quotes: true})
            .pipe(gulp.dest('./pages/views'));
    } else {
        return gulp.src(paths.pages)
            // .pipe(gulpif(
            //     true, 
            //     htmlmin({
            //         empty: true,
            //         spare: true,
            //         quotes: true
            //     })
            // ))
            .pipe(htmlmin({empty: true, spare: true, quotes: true}))
            .pipe(gulp.dest('./pages/views'));
    }
    
});

gulp.task('Rev', function () {
    if(sceneVariable=='development'){
        gulp.src([paths.revPath + '**/*.json','./public/**/*','!./public/image/**/*',
            '!./public/font/**/*.ttf',
            '!./public/font/**/*.eot',
            '!./public/font/**/*.woff',
            '!./public/font/**/*.svg'
        ])
            // .pipe(revCollector())
            .pipe(gulp.dest('./public'));
        gulp.src([paths.revPath + '**/*.json','./pages/**/*'])
            // .pipe(revCollector())
            .pipe(gulp.dest('./pages'));
    }else{
        gulp.src([paths.revPath + '**/*.json','./public/**/*','!./public/image/**/*',
            '!./public/font/**/*.ttf',
            '!./public/font/**/*.eot',
            '!./public/font/**/*.woff',
            '!./public/font/**/*.svg'
        ])
            .pipe(revCollector())
            .pipe(gulp.dest('./public'));
        gulp.src([paths.revPath + '**/*.json','./pages/**/*'])
            .pipe(revCollector())
            .pipe(gulp.dest('./pages'));
    }
        
});

gulp.task('clean', function () {
    return gulp.src(['./public','./pages'], {read: false})
        .pipe(clean());
});

gulp.task('cleanRev', function () {
    return gulp.src(paths.revPath, {read: false})
        .pipe(clean());
});

gulp.task('watch', function() {
    // // gulp.watch(paths.audio, ['audio']);
    // gulp.watch(paths.images, ['images']);
    // gulp.watch(paths.font, ['font']);
    // gulp.watch(paths.sass, ['sass']);
    // gulp.watch(paths.componentHtml, ['component']);
    // gulp.watch(paths.componentJs, ['component']);
    // gulp.watch(paths.componentScss, ['component']);
    // gulp.watch(paths.script, ['minifyjs']);
    // gulp.watch(paths.pages, ['pages']);
});

gulp.task('watch2', function() {
    gulp.watch(paths.sass, ['sass']);
    // gulp.watch(paths.script, ['minifyjs']);
    gulp.watch(paths.pages, ['pages']);
});

// 开发构建
gulp.task('dev', function (done) {
    sceneVariable = 'development';
    runSequence(
        ['clean'],
        ['wxVerify','audio', 'images', 'font', 'sass', 'component', 'minifyjs', 'pages'],
        ['watch'],
        done);
});

// 测试构建
gulp.task('test', function (done) {
    sceneVariable = 'test';
    runSequence(
        ['clean'],
        ['wxVerify','audio', 'images', 'font', 'sass', 'component', 'minifyjs', 'pages'],
        ['Rev'],
        done);
});

// 线上构建
gulp.task('production', function (done) {
    sceneVariable = 'production';
    runSequence(
        ['clean'],
        ['wxVerify','audio', 'images', 'font', 'sass', 'component', 'minifyjs', 'pages'],
        ['Rev'],
        done);
});

// 根据环境变量自动构建
gulp.task('accord', function (done) {
    if(sceneVariable=='development'){
        runSequence(
            ['clean'],
            ['wxVerify','audio', 'images', 'font', 'sass', 'component', 'minifyjs', 'pages'],
            ['watch'],
            done);
    }else{
        runSequence(
            ['clean'],
            ['wxVerify','audio', 'images', 'font', 'sass', 'component', 'minifyjs', 'pages'],
            ['Rev'],
            done);
    }
});
